package com.control;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;

@WebServlet("/fileUpload.do")
@MultipartConfig(location = "E://", fileSizeThreshold = 1024)
public class FileUploadServlet extends HttpServlet {
    public String getFileName(Part part) {
        String fileName = part.getHeader("content-disposition");
        //取文件名，[文件名第一个字母，引号)
        fileName = fileName.substring(fileName.lastIndexOf('=') + 2, fileName.length() - 1);
        return fileName;
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        Part part = req.getPart("file");
        String webPath = this.getServletContext().getRealPath("/");
        String filePath = webPath + "\\" + req.getParameter("dirName");
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdir();
        }
        String fileName = getFileName(part);
        part.write(filePath + "\\" + fileName);
        req.setAttribute("message", "文件上传成功");
        req.getSession().setAttribute("lastUploadName", filePath + "\\" + fileName);
        req.getSession().setAttribute("fileName", fileName);
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("fileUpload.jsp");
        requestDispatcher.forward(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
